package com.cyt.chattlibrary.face;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.text.style.ImageSpan;
import android.util.SparseArray;

import java.lang.ref.SoftReference;

public class EmotionManager {
    private static SparseArray<SoftReference<Drawable>> drawableMap = new SparseArray<>();

    public static ImageSpan getImageSpan(@NonNull Context context, @DrawableRes int resId, float textSize) {
        Drawable drawable = getDrawable(context, resId, textSize);
        return new CenterAlignImageSpan(drawable);
    }

    public static Drawable getDrawable(@NonNull Context context, int resId, float textSize) {
        SoftReference<Drawable> bitmapSoftReference = drawableMap.get(resId);
        if (bitmapSoftReference != null && bitmapSoftReference.get() != null) {
            return bitmapSoftReference.get();
        }
        Drawable drawable = null;
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
            drawable = new BitmapDrawable(context.getResources(), bitmap);
            drawable.setBounds(0, 0, (int) textSize, (int) textSize);
            bitmapSoftReference = new SoftReference<>(drawable);
            drawableMap.put(resId, bitmapSoftReference);
        } catch (Exception ignored) {
        }
        return drawable;
    }
}